package com.ebupt.migu.music.reco.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.reco.entity.RecoArtistESResultBean;
import com.ebupt.migu.music.reco.entity.RecoSongESResultBean;
import com.ebupt.migu.restapi.EsRestHttp;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2020/4/14
 */
@Slf4j
@Component
public class RecoESUtils {

    @Value("${spring.elasticsearch.port}")
    private int port;
    @Value("${spring.elasticsearch.reco_index_artist}")
    private String index_artist;
    @Value("${spring.elasticsearch.reco_index_song}")
    private String index_song;
    @Value("${spring.elasticsearch.hosts}")
    private String hosts;
    @Value("${spring.elasticsearch.schema}")
    private String schema;

    /**
     * 反查
     *
     * @param str
     * @return
     */
    public List<Map<String, String>> do_search(String str, int type) {
        try {
                  String date = DateUtil.getDateToday();
//            String date = "20211110";
            String index;
            if (type == 2) {
                index = index_song + date;
            } else {
                index = index_artist + date;
            }
            log.info("reco es search index:{}", index);
            log.info("index:{}, hosts:{}, port:{}, schema:{}", index, hosts, port, schema);
            log.info("反查JSON：{}", str);
//            String request_end_point = String.format("/%s/%s", index, "_search");
//            HttpEntity entity = new NStringEntity(str, ContentType.APPLICATION_JSON);
//            Request request = new Request("GET", request_end_point);
//            request.setEntity(entity);
//            String result = "";
//            RestClientBuilder builder = RestClient.builder(new HttpHost(hosts, port, schema));
//            RestClient restClient = builder.build();
//            try {
//                Response indexResponse = restClient.performRequest(request);
//                result = EntityUtils.toString(indexResponse.getEntity());
//            } catch (Exception e) {
//                e.printStackTrace();
//                log.error("反查失败：{}", e.getMessage());
//            } finally {
//                try {
//                    if (restClient != null) {
//                        restClient.close();
//                    }
//                } catch (Exception e) {
//                    log.error("rest client close error：{}", e.getMessage());
//                }
//            }
            EsRestHttp er = new EsRestHttp();
            String result = er.search(index,str,20);
            log.info("反查结果：{}", result);
            List<Map<String, String>> maps = new ArrayList<>();
            JSONArray array = JSONObject.parseObject(result).getJSONObject("hits").getJSONArray("hits");
            if (2 == type) {
                List<RecoSongESResultBean> songs = JSONObject.parseArray(array.toString(), RecoSongESResultBean.class);
                for (RecoSongESResultBean song : songs) {
                    Map<String, String> map = new HashMap<>();
                    map.put("rescId", song.get_source().getSong_id());
                    map.put("rescName", song.get_source().getSong_name());
                    maps.add(map);
                }
            } else {
                List<RecoArtistESResultBean> atrists = JSON.parseArray(array.toJSONString(), RecoArtistESResultBean.class);
                for (RecoArtistESResultBean artist : atrists) {
                    Map<String, String> map = new HashMap<>();
                    map.put("rescId", artist.get_source().getArtist_id());
                    map.put("rescName", artist.get_source().getArtist_name());
                    maps.add(map);
                }
            }
            return maps;
        } catch (Exception e) {
            log.error("ES查询资源详情失败：{}", e.getMessage());
            return null;
        }
    }

    /**
     * ES反查用户信息
     *
     * @return
     */
    public List<Map<String, String>> inverse_search(String str, int type) {
        log.info("反查参数：{}，参数类型：{}", str, type);
//        //拼装dsl json语句
//        JSONObject cons = new JSONObject();
//        cons.put("size", 20);
//        JSONObject match = new JSONObject();
//        JSONObject param = new JSONObject();
//        if (2 == type) {
//            param.put("song_name", str);
//        } else {
//            param.put("artist_name", str);
//        }
//        match.put("match", param);
//        cons.put("query", match);
//        log.info("查询内容：{}", cons.toString());
        String param = (2 == type ? "song_name=" : "artist_name=") + str;
        // 反查
        return do_search(param, type);
    }

    public static void main(String[] args) {
        String date = DateUtil.getDateToday();
        System.out.println(date);
    }
}
